// pages/payment/payment.js
var total_micro_second = 1;

/* 毫秒级倒计时 */
function countdown(that) {
  // 渲染倒计时时钟
  that.setData({
    clock: dateformat(total_micro_second)
  });

  if (total_micro_second <= 0) {
    that.setData({
      clock: "已经截止"
    });
    // timeout则跳出递归
    return;
  }
  setTimeout(function () {
    // 放在最后--
    total_micro_second -= 500;
    countdown(that);
  }
    , 500)
}

// 时间格式化输出，如3:25:19 86。每500ms都会调用一次
function dateformat(micro_second) {
  // 秒数
  var second = Math.floor(micro_second / 1000);
  // 小时位
  var hr = Math.floor(second / 3600 % 24);
  // 分钟位
  var min = Math.floor((second - Math.floor(second / 3600) * 3600) / 60);
  // 秒位
  var sec = (second - Math.floor(second / 3600) * 3600 - min * 60);// equal to => var sec = second % 60;

  var date = Math.floor(second / 3600 / 24)
  var data = { date, hr, min, sec }
  return data;
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //分享图片的数据
    hidden: true,
    img: ["../../image/a2_03.jpg", "../../image/a10_04.png", "../../image/a10_04.png"],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var globalData = getApp().globalData;
    var custId = globalData.custID;
    var url = globalData.apiurl + '/mobile/api/TeamBuy/GetPayMent';
    var that = this
    wx.request({
      url: url,
      data: {
        custId: custId,
        unionStoreID: options.unionStoreID,
        teamId: options.teamId,
        orderId:options.orderId
      },
      headers: {
        'Content-Type': 'application/json'
      },
      success: function (res) {
        var json = JSON.parse(res.data.content); 
        total_micro_second = Date.parse(json.Team.EndTime) - Date.parse(json.Now);
        console.log(json.Order)
        countdown(that);
        that.setData({
          TeamLeader: json.TeamLeader,
          Team: json.Team,
          UserList: json.UserList,
          Shop: json.Shop,
          Product: json.Product,
          DiscountedPrice: json.Product.CurrentPrice - json.Team.Discount,
          options: options,
          Order :json.Order,
          DeadLine :json.Deadline
        })


        //处理图片分享内容
        var img = new Array();
        img[0] = that.data.TeamLeader.HeadIMg;

        for (var i = 0; i < 2; i++) {
          if (that.data.UserList[i] != null) {
            img[i + 1] = that.data.UserList[i].HeadIMg;
          }
          else {
            img[i + 1] = "../../image/a10_04.png";
          }
        }

        that.setData({
          img: img
        })
      }
    });
  },
  sharePopk: function () {
    this.setData({
      sharepopkin: !this.data.sharepopkin
    });
  },
  share: function () {
    var that = this
    let data = this.data
    //下面是分享图片的内容
    let promise1 = new Promise(function (resolve, reject) {
      wx.getImageInfo({
        src: '../../image/23.jpg',
        success: function (res) {
          console.log(res)
          resolve(res);
        }
      })
    });
    //商品图片
    let promise2 = new Promise(function (resolve, reject) {
      wx.getImageInfo({
        src: data.Product.ProductImg,
        success: function (res) {

          resolve(res);
        }
      })
    });

    let promise3 = new Promise(function (resolve, reject) {
      wx.getImageInfo({
        src: '../../image/a9_03.png',
        success: function (res) {

          resolve(res);
        }
      })
    });

    let promise4 = new Promise(function (resolve, reject) {
      wx.getImageInfo({
        src: '../../image/a7_03.png',
        success: function (res) {

          resolve(res);
        }
      })
    });

    let promise6 = new Promise(function (resolve, reject) {
      wx.getImageInfo({
        src: data.img[0],
        success: function (sres) {
          resolve(sres);
        }
      })
    });

    let promise7 = new Promise(function (resolve, reject) {
      wx.getImageInfo({
        src: data.img[1],
        success: function (sres) {
          resolve(sres);
        }
      })
    });

    let promise8 = new Promise(function (resolve, reject) {
      wx.getImageInfo({
        src: data.img[2],
        success: function (sres) {
          resolve(sres);
        }
      })
    });

    let promise9 = new Promise(function (resolve, reject) {
      wx.getImageInfo({
        src: '../../image/a1_99.png',
        success: function (sres) {
          resolve(sres);
        }
      })
    });
   
    

    //二维码
    let promise5 = new Promise(function (resolve, reject) {
      var globalData = getApp().globalData;
      var custId = globalData.custID;
      wx.request({
        url: getApp().globalData.apiurl + '/mobile/api/TeamBuy/GetShareCrad',
        data: {
          page: "pages/Invitation/Invitation?custId="+ custId + " & unionStoreID=" + that.options.unionStoreID + "&teamId=" + that.options.teamId,
          smallAppId: "wx497292a17e20b072",
          smallSecret: "7bb71a2cc71ec050a34a8214e151d47f"
        },
        headers: {
          'Content-Type': 'application/json'
        },
        success: function (res) {
          resolve('data:image/jpg;base64,' + res.data.content)
        }
      })
      
    });
   
    Promise.all([
      promise1, promise2, promise3, promise4, promise5, promise6, promise7, promise8, promise9
    ]).then(res => {
      const ctx = wx.createCanvasContext('shareImg')
      //各个图文的位置
      ctx.drawImage('../../' + res[0].path, 0, 0, 420, 623)
      ctx.drawImage(res[1].path, 420 / 8, 160, 315, 150)
      ctx.drawImage('../../' + res[2].path, 260, 260, 90, 30)
      ctx.drawImage('../../' + res[3].path, 29, 446, 362, 24)
      ctx.drawImage(res[4], 277, 325, 90, 90)
      //用户头像
      for (var i = 0; i < 3; i++) {
        console.log(res[i + 5].path)
        if (data.img[i].indexOf("../") != -1) {
          ctx.drawImage('../../' + res[i + 5].path, (60 + (i * 50)), 500, 40, 40)
        }
        else {
          ctx.drawImage(res[i + 5].path, (60 + (i * 50)), 500, 40, 40)
        }
        if (i == 0) {
          ctx.drawImage('../../' + res[8].path, 66, 523, 30, 25)
          ctx.setTextAlign('left')
          ctx.setFillStyle('#ffffff')
          ctx.setFontSize(12)
          ctx.fillText('团长', 70, 540)
        }

      }


      //长按识别
      ctx.setTextAlign('left')
      ctx.setFillStyle('#000000')
      ctx.setFontSize(12)
      ctx.fillText('长按识别二维码', 277, 440)
      //商店名称
      ctx.setTextAlign('left')
      ctx.setFillStyle('#000000')
      ctx.setFontSize(15)
      if (data.Shop == null) {
        ctx.fillText('官方自营', 70, 145)
      } else {
        ctx.fillText(data.Shop.ShopName, 70, 145)
      }

      ctx.fillText(data.Team.TeamNumber + '人团', 300, 525)
      ctx.setFontSize(50)
      ctx.fillText('...', 220, 520)



      //商品名称
      ctx.setFontSize(14)
      var str = data.Product.ProductName;
      if (str.length > 13) {
        ctx.fillText(str.slice(0, 13), 60, 340)
        ctx.fillText(str.slice(13, 26), 60, 340 + 20)
      } else {
        ctx.fillText(str, 60, 340)
      }

      //拼团价
      ctx.setFillStyle('#ff0000')
      ctx.setFontSize(11)
      ctx.fillText('拼团价', 60, 400)
      ctx.setFontSize(18)
      ctx.fillText('￥' + (data.DiscountedPrice > 0 ? data.DiscountedPrice : 0), 95, 400)

      ctx.setFillStyle('#666666')
      ctx.setFontSize(13)
      ctx.fillText('单买价￥' + data.Product.CurrentPrice, 60, 425)
      var num = (data.Team.TeamNumber - data.UserList.length - 1);
      if (num > 0) {
        ctx.fillText('仅剩' + num + '名额，满人即发货', 60, 580)
      } else {
        ctx.fillText('已满人，请扫码发起组团', 60, 580)
      }


      //优惠价格
      ctx.setTextAlign('left')
      ctx.setFontSize(13)
      ctx.fillText('优惠￥' + data.Team.Discount, 270, 280)

      ctx.stroke()
      ctx.draw()

      let that = this
      wx.showLoading({
        title: '努力生成中...'
      })
      setTimeout(function () {
        wx.canvasToTempFilePath({
          x: 0,
          y: 0,
          width: 420,
          height: 623,
          destWidth: 420,
          destHeight: 623,
          canvasId: 'shareImg',
          success: function (res) {
            console.log(res.tempFilePath);
            that.setData({
              prurl: res.tempFilePath,
              hidden: false,

            })
            wx.hideLoading()
          },
          fail: function (res) {
            console.log(res)
          }
        })
      }, 2000)


    })

    this.setData({
      sharepopkin: !this.data.sharepopkin
    });


  },

  /**
   * 保存到相册
  */
  save: function () {
    var that = this
    //生产环境时 记得这里要加入获取相册授权的代码
    wx.saveImageToPhotosAlbum({
      filePath: that.data.prurl,
      success(res) {
        wx.showModal({
          content: '图片已保存到相册，赶紧晒一下吧~',
          showCancel: false,
          confirmText: '确定',
          confirmColor: '#72B9C3',
          success: function (res) {
            if (res.confirm) {
              console.log('用户点击确定');
              that.setData({
                hidden: true
              })
            }
          }
        })
      }
    })

  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    var globalData = getApp().globalData;
    var custId = globalData.custID;
    var that = this
    console.log(that.options.custId)
    return {
      title: '一起来拼团吧',
      path: '/pages/Invitation/Invitation?custId=' + custId + "&unionStoreID=" + that.options.unionStoreID + "&teamId=" + that.options.teamId
    }
  },
  
})